package logic

import (
	"context"
	"errors"
	"hm-zero-mall/apps/user/models"
	"hm-zero-mall/apps/user/rpc/internal/svc"
	"hm-zero-mall/apps/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// Register 注册
func (l *RegisterLogic) Register(in *pb.UserRegisterRequest) (*pb.UserInfo, error) {
	user, err := l.svcCtx.UserModel.FindOneByPhone(l.ctx, in.Phone)
	if err != nil {
		return nil, err
	}
	if user != nil && user.Id > 0 {
		return nil, errors.New("用户已存在")
	}

	_, err = l.svcCtx.UserModel.Insert(l.ctx, &models.User{
		Username: in.Username,
		Password: in.Password,
		Phone:    in.Phone,
	})
	if err != nil {
		return nil, err
	}

	newUser, err := l.svcCtx.UserModel.FindOneByPhone(l.ctx, in.Phone)
	if err != nil {
		return nil, err
	}
	return &pb.UserInfo{
		Id:       newUser.Id,
		Phone:    newUser.Phone,
		Username: newUser.Username,
		Status:   newUser.Status,
	}, nil
}
